Svelte: A Beginner's Guide by Simon Holthausen

Svelte: A Beginner's Guide by Simon Holthausen

Author:Simon Holthausen [Simon Holthausen]
Language: eng
Format: epub
Publisher: SitePoint
Published: 2022-02-10T00:00:00+00:00


The app surely won’t win us any design awards, but it helps us showcase the problem we have with global state in this application. The root of the application looks like this:

<script> import Topbar from './Topbar.svelte'; import AuthOnly from './AuthOnly.svelte'; </script> <Topbar /> <div> <p> This part of the page is always visible </p> </div> <div> <p> This part is only visible to logged in users </p> <AuthOnly /> </div> <style> div { border: 1px solid blue; padding: 5px 10px } </style>

That component uses other components. To do so, we import them as a default import in the <script> tag. We can then use them by the same name as the default import in the template. (We’ll look into component interaction more deeply in Part 5 of this series.)

Topbar.svelte looks like this:

<div> How to get the username in here? </div> <style> div { background: lightgrey; padding: 5px 10px; text-align: right; } </style>

And AuthOnly.svelte looks like this:

<script> let authenticated = false; </script> {#if authenticated} <p> Super secret stuff! </p> {:else} <button on:click={() => authenticated = true}>Log In</button> {/if}

The components Topbar and AuthOnly both need access to the user state; passing it via properties is not an option. In this simple example, we only need to pass the user state down one component, but in reality this will almost never be the case. So we need some other place to share the state. Additionally, AuthOnly needs to update the state to log in the user. Where do we put the state now? It’s probably best to put it inside a JavaScript file that exports the state so everyone can access it. Let’s try that!



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.